import React from 'react';
import { Tools, Bubble } from 'weaver-mobile';
import { openLink } from '../../../../util';
import search_png from './search.png';
import './index.css';

class TodoCount extends React.Component {
  constructor(props) {
    super(props);
    this.onLoadData = this.onLoadData.bind(this);
    this.onOpen = this.onOpen.bind(this);
    this.state = {
      data: [],
      counts: {}
    };
  }

  componentWillMount() {
    this.onLoadData();
  }

  componentWillReceiveProps() {
    this.onLoadData();
  }

  render() {
    const { data = [], counts = {} } = this.state;
    const url = '/spa/esearch/static4mobile/index.html#/esearch?type=RSC';

    return (
      <div className="todocount">
        <ul>
          {data.map(item => {
            return (
              <li key={item.id} onClick={() => item.linkUrl && this.onOpen(item.linkUrl)}>
                <span>{counts[item.id] || 0}</span>
                <span>{item.abbr}</span>
              </li>
            );
          })}
        </ul>
        <img src={search_png} alt="" onClick={() => this.onOpen(url)} />
      </div>
    );
  }

  onLoadData() {
    Tools.callApi({
      url: '/api/portal/element/todocount/getViewData',
      method: 'GET',
      params: { type: 'mobile' },
      type: 'json'
    }).then(result => {
      const { data = [] } = result;
      this.setState({ data });

      data.forEach(item => {
        Tools.callApi({
          url: item.countApi,
          method: item.countApiMethod,
          params: {},
          type: 'json'
        }).then(result => {
          this.setState(prevState => ({
            counts: Object.assign({}, prevState.counts, { [item.id]: result.count || 0 })
          }));
        });
      });
    });
  }

  onOpen(url) {
    openLink(url);
  }
}

export default TodoCount;
